import React, { Suspense } from "react";
import { Routes, Route, Navigate } from "react-router-dom";
import { Spin } from "antd";
import components from "./components";

// 懒加载动画
function LazyCom({ children }) {
	return (
		<Suspense
			fallback={
				<div className="min-w-full min-h-screen flex justify-center items-center">
					<Spin tip="玩命加载中..."></Spin>
				</div>
			}
		>
			{children}
		</Suspense>
	);
}

// 登陆拦截
function IsLogin({ children }) {
	const isLogin = localStorage.getItem("isLogin");
	return isLogin === "true" ? (
		<LazyCom children={children} />
	) : (
		<Navigate to="/login" replace />
	);
}

// 递归生成路由
function createRoute(components) {
	// 不是数组就直接返回
	if (!Array.isArray(components)) {
		return;
	}
	// 生成路由表
	return components.map((c) => {
		return c.isLogin === true ? (
			<Route
				key={c.path}
				path={c.path}
				element={<IsLogin children={<c.component />} />}
			>
				{createRoute(c?.children)}
			</Route>
		) : (
			<Route
				key={c.path}
				path={c.path}
				element={<LazyCom children={<c.component />} />}
			>
				{createRoute(c?.children)}
			</Route>
		);
	});
}

export default () => {
	return (
		<>
			<Routes>
				{/* 递归生成嵌套路由 */}
				{createRoute(components)}
			</Routes>
		</>
	);
};
